package com.yfz.day01;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 三数之和 15
 */

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> result = new ArrayList<>();
        int len = nums.length;
        for(int i = 0;i< len -2 ;i++)
        {
            int x = nums[i];
            if(i > 0 && nums[i-1] == x)continue;
            int j = i+1, k =len -1 ;
            while(j<k)
            {
                int sum = nums[j]+nums[k];
                if(sum>-nums[i])k--;
                else if(sum<-nums[i])j++;
                else result.add(Arrays.asList(x,nums[j++],nums[k--]));
                j++;
                while(j<k && nums[j-1] == nums[j]) j++;
                k--;
                while(j<k && nums[k-1] == nums[k]) k--;
            }
        }
        return result;
    }
}